import { useRef, useState, useEffect } from 'react';
import { Image, StyleSheet, Platform, Text, View, TouchableOpacity, Dimensions, Alert } from 'react-native';
import { Stack } from 'expo-router';
import { SafeAreaView } from 'react-native-safe-area-context';
import { FFmpegKit, ReturnCode } from 'ffmpeg-kit-react-native';
import * as FileSystem from 'expo-file-system';
import * as MediaLibrary from 'expo-media-library';
import { router } from 'expo-router';
import AntDesign from '@expo/vector-icons/AntDesign';
import { ThemedView } from '@/components/ThemedView';
import Upload from "@/components/Upload"
import ProgressBar from '@/components/ProgressBar';
import ProcessingQueue from '@/utils/processingQueue'
import { getOutputPath } from '@/utils/ffmpeg'

const { width } = Dimensions.get('window'); // 获取屏幕宽度

const styles = StyleSheet.create({
  container: {
    flex: 1,
    position: 'relative',
  },
  content: {
    flex: 1,
    padding: 20,
    backgroundColor: '#fff',
  },
  backButton: {
    padding: 16,
  },
  btnBox: {
    marginTop: 28,
    // flexDirection: 'row',
    gap: 6,
  },
  repetition: {
    borderWidth: 1,
    borderColor: "#5d5ce5",
    width: width - 40,
    padding: 10,
    backgroundColor: "#5d5ce5",
    alignItems: 'center',
    borderRadius: 8,
  },
  md5: {
    borderWidth: 1,
    borderColor: "#5d5ce5",
    width: width - 40,
    padding: 10,
    backgroundColor: "white",
    alignItems: 'center',
    borderRadius: 8,
  },
  both: {
    width: width - 40,
    padding: 10,
    backgroundColor: "#5d5ce5",
    borderRadius: 8,
    alignItems: 'center',
  },
  bottomButtonContainer: {
    position: 'absolute',
    bottom: 30,
    paddingLeft: 30,
    paddingRight: 30,
    alignSelf: 'center',
    borderTopWidth: 1,          // 顶部边框
    borderTopColor: '#e0e0e0',  // 边框颜色（浅灰色）
    paddingTop: 15,             // 边框与按钮的间距
  },
  bottomButton: {
    // position: 'absolute', // 绝对定位
    // bottom: 30,          // 距离底部30px
    // width: width - 40,   // 屏幕宽度减去40px（左右各留20px）
    // alignSelf: 'center', // 水平居中
    // padding: 15,
    // backgroundColor: "#5d5ce5",
    // borderRadius: 8,
    // alignItems: 'center',

    width: width - 40,             // 填满容器宽度
    padding: 15,
    backgroundColor: "#5d5ce5",
    borderRadius: 8,
    alignItems: 'center',
  },
  disabledButton: {
    opacity: 0.5,
    backgroundColor: 'gray',
  }
});





const ToolsPage = () => {
  const uploadRef = useRef<React.ElementRef<typeof Upload>>(null);
  const [progress, setProgress] = useState({ current: 0, total: 0, message: '' });
  const [isDisabled, setIsDisabled] = useState(true);
  const [isPaused, setIsPaused] = useState(false);
  const processingQueue = useRef(new ProcessingQueue()).current;


  const resetProcessingQueue = () => {
    setIsDisabled(true)
    setProgress({
      current: 0,
      total: 0,
      message: '完成'
    });
  }

  const processVideos = async (operation) => {
    const selectedVideos = uploadRef?.current?.getVideos()
    if (selectedVideos.length === 0) {
      Alert.alert('还未选择视频', '', [
        {
          text: '确认',
        },
      ]);
    }
    setProgress({ current: 0, total: selectedVideos.length, message: '处理中...' });
    setIsDisabled(true);
    try {
      selectedVideos?.forEach((video, index) => {
        const outputPath = getOutputPath(video.uri, operation);
        processingQueue.addTask({
          // task: async () => {
          //   if (operation === 'reduce') {
          //     await reduceDuplication(video.uri, outputPath);
          //   } else if (operation === 'md5') {
          //     await changeMD5(video.uri, outputPath);
          //   } else if (operation === 'bothProccess') {
          //     await bothProccess(video.uri, outputPath);
          //   }
          // },
          id: `task-${Date.now()}-${index}`,
          inputPath: video.uri,
          outputPath: outputPath,
          operation,
          status: 'pending' as const,
          index
        });
      })
    } catch (e) {
      console.log(e)
    }

    // Alert.alert('处理完成', '', [
    //   {
    //     text: '确认',
    //     onPress: () => {
    //       resetProcessingQueue()
    //     }
    //   },
    // ]);
  };

  const onSelectedFiles = (isSelected: boolean) => {
    setIsDisabled(isSelected)
    setProgress({
      current: 0,
      total: 0,
      message: '完成'
    });
  }

  const back = () => {
    processingQueue?.reset()
    resetProcessingQueue()
    uploadRef?.current?.clear()
    router.back()
  }



  useEffect(() => {
    processingQueue.onProgress = (index) => {
      const selectedVideos = uploadRef?.current?.getVideos()
      setProgress({
        current: index + 1,
        total: selectedVideos.length,
        message: '完成'
      });
      if (index + 1 === selectedVideos.length) {
        Alert.alert('处理完成,数据已保存至相册', '', [
          {
            text: '确认',
            onPress: () => {
              processingQueue.reset()
              resetProcessingQueue()
              uploadRef?.current?.clear()
            }
          },
        ]);

      }
    };
    processingQueue.onPausecb = (isPaused) => {
      setIsPaused(isPaused)
    }
  }, []);


  return (
    <SafeAreaView edges={['top']} style={styles.container}>
      <TouchableOpacity
        style={styles.backButton}
        onPress={back} // 返回上一页
      >
        <AntDesign name="left" size={24} color="black" />
      </TouchableOpacity>
      <ThemedView style={styles.content}>
        <Upload ref={uploadRef} onSelect={onSelectedFiles} isDisabled={isDisabled} resetProcessingQueue={resetProcessingQueue} />
        {progress.total > 0 && (
          <ProgressBar
            current={progress.current}
            total={progress.total}
            message={progress.message}
            onPause={() => processingQueue.pause()}
            onResume={() => processingQueue.resume()}
            onCancel={() => {
              uploadRef?.current?.clear()
              resetProcessingQueue()
              processingQueue.cancelAll();
            }}
            isPaused={isPaused}
          />
        )}
        <View style={styles.btnBox}>
          <TouchableOpacity style={[styles.repetition, isDisabled && styles.disabledButton]} onPress={() => processVideos('reduce')} disabled={isDisabled}   ><Text style={{ color: "white", fontSize: 16 }}>一键降低重复度</Text></TouchableOpacity>
          <TouchableOpacity style={[styles.md5, isDisabled && styles.disabledButton]} onPress={() => processVideos('md5')} disabled={isDisabled}  ><Text style={{ color: "#5d5ce5", fontSize: 16 }}>一键修改MD5</Text></TouchableOpacity>
          <TouchableOpacity style={[styles.both, isDisabled && styles.disabledButton]} onPress={() => processVideos('reduce')} disabled={isDisabled}  ><Text style={{ color: "white", fontSize: 16 }}>组合修改</Text></TouchableOpacity>
        </View>
      </ThemedView>
      {/* <View style={styles.bottomButtonContainer}>
        <TouchableOpacity style={styles.bottomButton}>
          <Text style={{ color: "white", fontSize: 16 }}>一键导出</Text>
        </TouchableOpacity>
      </View> */}
    </SafeAreaView >
  )
}

export default ToolsPage;